//
//  AddAppPage.swift
//  sui04mac
//
//  Created by 杨剑 on 2023/11/22.
//

import SwiftUI
import Alamofire

//@ObservableObject
class AddAppModel : ObservableObject {
//    @Published var
//    @Published var appModel:AppModel  = AppModel(id: generateID(),appkey: "1168171101115760#dabaojian",client_id: "YXA6uUquUL6lEeeIi-vMCP7JJg",client_secret: "YXA6qb6yfKTMOhCdZibj9Q5Z9YNfzoA")
    @Published var display_name = "测试"
    @Published var appkey = "1168171101115760#dabaojian"
    @Published var client_id = "YXA6uUquUL6lEeeIi-vMCP7JJg"
    @Published var client_secret = "YXA6qb6yfKTMOhCdZibj9Q5Z9YNfzoA"
    var org_name : String {
        appkey.components(separatedBy: "#").first ?? ""
    }
    var app_name : String {
        appkey.components(separatedBy: "#").last ?? ""
    }
}

struct AddAppPage: View {
    
    struct Row : View{
        var placeholder : String

        @Binding var text : String
        var body: some View{
            HStack{
                Text(placeholder)
                TextField("请填入\(placeholder)", text: $text)
            }
        }
    }
    @ObservedObject var viewModel = AddAppModel()
    @State var showText = "配置成功"
//    @State private var appModel:AppModel = AppModel(id: generateID())
    
//    @State var appkey = ""
//    @State var appkey = ""
//    @State var appkey = ""

    @Environment(AppkeyModelData.self) var modelData
//    @StateObject var hudManager = HUDManager()
    @State private var showLoading = false
    @State private var showHUD = false
    @State private var showEnd = false
    @State private var configSuccess = false
    @Environment(\.dismiss) var dismiss
    var body: some View {
        
        
        VStack{
            Row(placeholder: "名称",text: $viewModel.display_name)
            Row(placeholder: "Appkey",text: $viewModel.appkey)
            Row(placeholder: "Client ID",text: $viewModel.client_id)
            Row(placeholder: "ClientSecret",text: $viewModel.client_secret)

            HStack{
                Spacer()
                Button(action: {

                    print("\(viewModel.appkey)")
                    print("\(viewModel.client_id)")
                    print("\(viewModel.client_secret)")
                    
                    if let md = modelData.appModels.first(where: {$0.appkey == viewModel.appkey}){
                        showText = "失败:appkey已经存在"
                        configSuccess = false
                        showEnd = true
                        return
                    }
                    if viewModel.appkey.isEmpty {
                        showText = "失败:appkey是空的"
                        configSuccess = false
                        showEnd = true
                        return
                    }
                    if viewModel.client_id.isEmpty {
                        showText = "失败:Client ID是空的"
                        configSuccess = false
                        showEnd = true
                        return
                    }
                    if viewModel.client_secret.isEmpty {
                        showText = "失败:ClientSecret是空的"
                        configSuccess = false
                        showEnd = true
                        return
                    }
                    
                    showLoading = true
                    fetchCluster(appkey:viewModel.appkey) { cluster in
                        guard let cluster else{
                            showText = "失败:cluster获取失败"
                            configSuccess = false
                            showLoading = false
                            return
                        }
                        fetchAppToken(base_url: cluster.base_url, org_name: viewModel.org_name, app_name: viewModel.app_name) { access_token in

                            guard let access_token else{
                                showText = "失败:access_token获取失败"
                                configSuccess = false
                                showLoading = false
                                return
                            }
                            showText = "配置成功"
                            configSuccess = true
                            showLoading = false
                            
                            var appModel = AppModel(id: generateID())
                            appModel.cluster = cluster
                            appModel.display_name = viewModel.display_name
                            appModel.appkey = viewModel.appkey
                            appModel.client_id = viewModel.client_id
                            appModel.client_secret = viewModel.client_secret
                            appModel.access_token = access_token
                            print(appModel)
//                            modelData.appModels.append(appModel)
                            modelData.addAppModels(app: appModel)
                            
                            if modelData.currentAppModelID < 1 {
                                modelData.updateCurrentAppModelID(id: appModel.id)
//                                modelData.currentAppModelID = appModel.id
                            }
                        }
                    }
                    
//                    fetchCluster(appkey: "",completionHandler: {response in
//                        
//                        print(response)
//                        showLoading = false
//                    })

//                    DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
//                        showLoading = false
//                    }
//                    hudManager.show("Working...")
//                    modelData.appModels.append(appModel)
//                    dismiss()
                }, label: {
                    Text("完成")
                })
                .toast(isPresented: $showLoading,onDismiss: {
                    showEnd = true
                },content: {
                    ToastView("处理中(会联网)...")
                      .toastViewStyle(.indeterminate)
                })
                .toast(isPresented: $showEnd ,dismissAfter: 1.0,onDismiss: {
                    if configSuccess {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            self.dismiss()
                        }
                    }
                }) {
                    if configSuccess {
                        ToastView(showText)
                          .toastViewStyle(.success)
                    }else{
                        ToastView(showText)
                          .toastViewStyle(.failure)
                    }
                }
            }
        }.padding()
            .navigationTitle("配置appkey")
    }
    
    func fetchCluster(appkey:String,completionHandler: @escaping (ClusterModel?) -> Void) {
//        appModel.appkey
        struct DecodableType: Decodable { let cluster_name: String }
        AF.request("http://rs.easemob.com/easemob/server.json?app_key=\(appkey.replacingOccurrences(of: "#", with: "%23"))",method: .get)
            .responseDecodable(of: DecodableType.self) { response in
                if let cluster_name = response.value?.cluster_name {
                    completionHandler(sui04mac.fetchCluster(cluster_id: cluster_name))
                }else{
                    print("{失败}")
                    completionHandler(nil)
                }
            }
//            .responseJSON(completionHandler: <#T##(AFDataResponse<Any>) -> Void#>)
//            .responseData { response in
//                if let data = response.data {
//                    print(data)
//
//                }
//            }
//            .response(completionHandler: { response in
//                if let data = response.data {
//                    print(data)
//                }
//            completionHandler(response)
//        })
    }
    
    func fetchAppToken(base_url: String,org_name:String ,app_name:String,completionHandler: @escaping (String?) -> Void){
//        POST https://{host}/{org_name}/{app_name}/token
        let urlString = base_url + "/" + org_name + "/" + app_name + "/token"
        let parameters = [
            "grant_type": "client_credentials",
            "client_id": viewModel.client_id,
            "client_secret": viewModel.client_secret,
        ]
        
        struct DecodableType: Decodable { let access_token: String }
        
        
        AF.request(urlString,method: .post,parameters: parameters,encoder: JSONParameterEncoder.default)
            .responseDecodable(of:DecodableType.self) { response in
                completionHandler(response.value?.access_token)
            }
            .cURLDescription(calling: { curlString in
                print(curlString)
            })
    }
}


#Preview {
    AddAppPage()
}
/*
  
 1.经常不在线,最严重,
 
 - 疑似丢消息
 
 3.后台看在线用户,是否准确?实际收不到消息
    
 如果发现收不到消息后,一直收不到消息了
 
 客户同时在线70~80家
 
 回复 一直链接,可能存在假死情况
 方案 业务层做重连,隔一段时间做一次重连
 
 当前客户每天早晨会刷新重连一次
 
 回复 这个时间有点长
 建议 2~3小时重连一次
 
 
 
 
 
 
 
 */
